<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <title>携程礼品卡</title>
    <link rel="stylesheet" href="model.css">
    <style>
        body {
            min-width: 960px;
        }

        .add {
            background-color: #7f76dc;
            padding: 5px 10px;
            float: right;
            color: white;
            font-weight: 300;
            font-size: 16px;
        }

        .add:hover {
            background-color: #179521;
        }

        table {
            text-align: center;
            width: 100%;
            border-collapse: collapse;
            border-spacing: 0;
            word-break: break-all;
            word-wrap: break-word;
            font-size: 14px;
            font-family: "Microsoft JhengHei UI", serif;
        }

        table th {
            font-weight: bold;
            background: #efefef;
            padding: 6px;
            border: 1px solid #dfdfdf;
        }

        table td {
            border: 1px solid #dfdfdf;
            padding: 6px;
        }

        .opt {
            background-color: #7f76dc;
            padding: 3px 7px;
            color: white;
            border-radius: 3px;
            margin: 0 2px;
        }

        .ok {
            background-color: #179521;
            color: white;
            padding: 2px 5px;
            line-height: 18px;
            word-break: break-all;
            font-size: 14px;
        }

        .err {
            background-color: #F40;
            color: white;
            padding: 2px 5px;
            line-height: 18px;
            word-break: break-all;
            font-size: 12px;
        }

        .sort {
            list-style: none;
            padding-left: 0;
            margin: 0;
        }

        .sort li a {
            color: blue;
        }

        .sort li {
            display: inline-block;
            margin-right: 10px;
            border: 1px solid #777;
            padding: 5px 10px;
            border-radius: 3px;
            font-size: 12px;
        }

        label {
            border: 1px solid #777;
            color: blue;
            padding: 5px 10px;
            font-size: 12px;
            border-radius: 3px;
        }

        .active {
            background-color: #7f76dc;
        }

        .active a {
            color: white !important;
        }

        .pagination {
            list-style: none;
            padding-left: 0;
            display: inline-block;
            border-radius: 4px;
            font-size: 12px;
        }

        .pagination li {
            float: left;
        }

        .pagination li a {
            padding: 4px 8px;
            text-decoration: none;
            border: 1px solid #ddd;
            color: #7f76dc;
        }

        .menu div {
            text-align: center;
            float: left;
            width: 33%;
            margin: 0 auto;
        }

        .menu h3 {
            margin: 0 0 5px;
        }
    </style>
</head>
<body>
<?php

include_once 'Xiecheng.php';
include_once "Pagination.php";

use lifanko\Xiecheng;
use lifanko\Pagination;

$xiecheng = new Xiecheng();

$db_config = json_decode(file_get_contents('db.json'));
$pdo = $xiecheng->pdo($db_config->host, $db_config->dbname, $db_config->username, $db_config->password);
$tb = 'list';

$time = time();

if (isset($_GET['cookie'])) {
    if (!empty($_POST['new']) && !empty($_POST['account']) && !empty($_POST['password']) && !empty($_POST['passpay']) && !empty($_POST['cookies'])) {
        if ($_POST['cookies'] == 'SET-PAY-PASSWORD') {
            $is_cookie_ok = 1;
        } else {
            $money = $xiecheng->get_money($_POST['cookies']);
            $money = json_decode($money, true);
            $is_cookie_ok = $money['code'] == 0;
        }

        if ($is_cookie_ok) {
            if ($_POST['new'] == 'no') {
                if ($_POST['cookies'] == 'SET-PAY-PASSWORD') {
                    $sql = "UPDATE $tb SET pay=:pay WHERE account=:account AND password=:password";

                    $stmt = $pdo->prepare($sql);
                    $res = $stmt->execute(['pay' => $_POST['passpay'], 'account' => $_POST['account'], 'password' => $_POST['password']]);

                    if ($res) {
                        echo '<h1>设置支付密码成功</h1>';
                    } else {
                        echo '<h1>设置支付密码失败</h1>';
                    }
                } else {
                    $sql = "UPDATE $tb SET pay=:pay,cookie=:cookie,updatetime=$time WHERE account=:account AND password=:password";

                    $stmt = $pdo->prepare($sql);
                    $res = $stmt->execute(['pay' => $_POST['passpay'], 'cookie' => $_POST['cookies'], 'account' => $_POST['account'], 'password' => $_POST['password']]);

                    if ($res) {
                        echo '<h1>更新cookie成功</h1>';
                    } else {
                        echo '<h1>更新cookie失败</h1>';
                    }
                }
            } else if ($_POST['new'] == 'yes') {
                $cookie = $_POST['cookies'];
                $account = $_POST['account'];
                $password = $_POST['password'];

                $info = $xiecheng->get_info($cookie);
                $info = json_decode($info, true);

                if ($info['result']['resultCode'] == -1) {
                    echo '<h1>查询账户信息失败，请检查</h1>';
                } else {
                    if (!empty($info['thisUserInfo']['mobilePhone'])) {
                        if ($info['thisUserInfo']['mobilePhone'] != $account && $info['uID'] != $account) {
                            echo '<h1>账号数据不符，添加失败</h1><span class="err">输入账号：' . $account . '，cookie对应的账号：' . $info['thisUserInfo']['mobilePhone'] . '(uID: ' . $info['uID'] . ')</span>';
                            echo "<p><a href='index.php' style='color: blue'>点击返回礼品卡管理</a></p>";
                            die();
                        }
                    }

                    $name = $info['thisUserInfo']['username'];
                    $birth = $info['thisUserInfo']['birth'];
                    $gender = $info['thisUserInfo']['gender'];
                    $city = $info['thisUserInfo']['city'];
                    $email = $info['thisUserInfo']['email'];
                    $updatetime = $time;
                    if (count($money['data']['giftCardValidityInfoList'])) {
                        $money_left = $money['data']['giftCardValidityInfoList'][0]['availableAmount'];
                        $type = $money['data']['giftCardValidityInfoList'][0]['ticketCategoryName'];
                        $expiration = $money['data']['giftCardValidityInfoList'][0]['expirationDate'];
                        $status = $money['data']['giftCardValidityInfoList'][0]['statusDesc'];
                    } else {
                        $money = $xiecheng->get_amount($cookie);
                        $money = json_decode($money, true);
                        if ($money['code'] == 0) {
                            $money_left = $money['data']['ticketAvailableList'][0]['availableAmount'];
                            $type = $money['data']['ticketAvailableList'][0]['ticketCategoryName'];
                            $expiration = '1999-09-09';
                            $status = '-';
                        } else {
                            echo '<h1>添加失败</h1><span class="err">无法读取余额</span>';
                            echo "<p><a href='index.php' style='color: blue'>点击返回礼品卡管理</a></p>";
                            die();
                        }
                    }

                    $sql = "SELECT name FROM $tb WHERE account=:account";
                    $stmt = $pdo->prepare($sql);
                    $stmt->execute(['account' => $account]);
                    $res = $stmt->fetch(PDO::FETCH_ASSOC);

                    if (empty($res)) {
                        $sql = "INSERT INTO $tb (name,account,password,cookie,updatetime,money,type,expiration,status,birth,gender,city,email) VALUE (:name,:account,:password,:cookie,:updatetime,:money,:type,:expiration,:status,:birth,:gender,:city,:email)";

                        $stmt = $pdo->prepare($sql);
                        $res = $stmt->execute(['name' => $name, 'account' => $account, 'password' => $password, 'cookie' => $cookie, 'updatetime' => $updatetime, 'money' => $money_left, 'type' => $type, 'expiration' => $expiration, 'status' => $status, 'birth' => $birth, 'gender' => $gender, 'city' => $city, 'email' => $email]);

                        if ($res) {
                            echo '<h1>添加成功</h1><span class="ok">账号：' . $account . '，昵称：' . $name . '</span>';
                        } else {
                            echo '<h1>添加失败</h1>';
                        }
                    } else {
                        echo '<h1>账号已存在</h1><span class="err">账号：' . $account . '，昵称：' . $name . '</span>';
                    }
                }
            } else {
                echo '<h1>设置cookie失败：未定义选项</h1>';
            }
        } else {
            echo '<h1>输入的cookie不可用</h1><span class="err">' . $_POST['cookies'] . '</span>';
        }
    } else {
        echo '<h1>设置cookie失败：参数不足</h1>';
    }

    echo "<p><a href='index.php' style='color: blue'>点击返回礼品卡管理</a></p>";
    die();
}

session_start();

if (!empty($_GET['sort'])) {
    $sort = $_GET['sort'];
    $_SESSION['sort'] = $sort;
} else {
    if (!empty($_SESSION['sort'])) {
        $sort = $_SESSION['sort'];
    } else {
        $sort = 1;
    }
}

if (!empty($_GET['min'])) {
    if ($_GET['min'] == 'no') {
        $_SESSION['min'] = $min = '';
    } else {
        $_SESSION['min'] = $min = $_GET['min'];
    }
} else {
    if (!empty($_SESSION['min'])) {
        $min = $_SESSION['min'];
    }
}
$min_sql = empty($min) ? '' : " WHERE money>=" . $min;

$account_sql = empty($_GET['account']) ? '' : (empty($min_sql) ? " WHERE account='" . $_GET['account'] . "'" : " AND account=" . $_GET['account'])
?>

<h1 style="text-align: center">管理 - 携程礼品卡</h1>

<div class="menu">
    <div>
        <h3>排序</h3>
        <ul class="sort">
            <li <?php echo $sort == 1 ? 'class="active"' : ''; ?>><a href="index.php?sort=1">余额递增</a></li>
            <li <?php echo $sort == 2 ? 'class="active"' : ''; ?>><a href="index.php?sort=2">余额递减</a></li>
        </ul>
    </div>
    <div>
        <h3>筛选</h3>
        <form method="get" action="index.php">
            <?php
            if (empty($min)) {
                echo '<label>余额大于:</label>
                <input type="number" name="min" min="0" style="padding: 4px">
                <input type="submit" value="确定" style="padding: 3px 10px;">';
            } else {
                echo '<label style="color: white;background-color: #7f76dc;">余额大于' . $min . '</label>
                <input type="hidden" name="min" value="no">
                <input type="submit" value="取消" style="padding: 4px 10px;font-size: 12px;">';
            }
            ?>
        </form>
    </div>
    <div>
        <h3>搜索</h3>
        <form method="get" action="index.php">
            <label>账号搜索 :</label>
            <?php
            if (empty($_GET['account'])) {
                echo '<input type="text" name="account" placeholder="请输入账号" autocomplete="off" style="padding: 4px">
                <input type="submit" value="确定" style="padding: 4px 10px;font-size: 12px;">';
            } else {
                echo '<input type="text" name="account" placeholder="' . $_GET['account'] . '" autocomplete="off" style="padding: 4px">
                <a href="index.php"><label style="font-size: 12px;background-color: #7f76dc;color: white;cursor: pointer">重置</label></a>';
            }
            ?>
        </form>
    </div>
</div>
<div style="clear: both"></div>

<h3>礼品卡列表<a href="app.php" class="add">添加礼品卡</a></h3>
<table>
    <tr>
        <th>#</th>
        <th>账号</th>
        <th>账户名</th>
        <th>余额</th>
        <th>卡类型</th>
        <th>卡到期</th>
        <th>卡状态</th>
        <th>cookie</th>
        <th>操作</th>
    </tr>
    <?php
    if (!empty($_GET['p'])) {
        $page = $_GET['p'];
    } else {
        $page = 1;
    }
    $page_size = 20;
    $sql = "SELECT count(*) as total FROM $tb" . $min_sql . $account_sql;
    $stmt = $pdo->query($sql);
    $total = $stmt->fetch(PDO::FETCH_ASSOC)['total'];

    $page_sql = " LIMIT " . (($page - 1) * $page_size) . "," . $page_size;
    $sort_sql = $sort == 1 ? " ORDER BY money" : ($sort == 2 ? " ORDER BY money DESC" : '');

    $sql = "SELECT * FROM $tb" . $min_sql . $account_sql . $sort_sql . $page_sql;

    foreach ($pdo->query($sql) as $row) {
        $money = $xiecheng->get_money($row['cookie']);
        $money = json_decode($money, true);
        $is_cookie_ok = $money['code'] == 0;

        if ($is_cookie_ok && count($money['data']['giftCardValidityInfoList'])) {
            $money_left = $money['data']['giftCardValidityInfoList'][0]['availableAmount'];
        } else {
            $money = $xiecheng->get_amount($row['cookie']);
            $money = json_decode($money, true);
            $is_cookie_ok = $money['code'] == 0;
            $money_left = $money['data']['ticketAvailableList'][0]['availableAmount'];
        }

        // 若网络查询余额与数据库不同，则更新数据库
        if ($is_cookie_ok && is_numeric($money_left) && $row['money'] != $money_left) {
            $sql_update = "UPDATE $tb SET money=:money WHERE account=:account AND password=:password";
            $stmt = $pdo->prepare($sql_update);
            $stmt->execute(['money' => $money_left, 'account' => $row['account'], 'password' => $row['password']]);
        }

        echo "<tr>";

        echo "<td>{$row['id']}</td>";
        echo "<td>{$row['account']}</td>";
        echo "<td>{$row['name']}</td>";
        echo "<td>{$money_left}</td>";
        echo "<td>{$row['type']}</td>";
        echo "<td>{$row['expiration']}</td>";
        echo "<td>{$row['status']}</td>";

        $available = 30 * 24 - intval((time() - $row['updatetime']) / 60 / 60) - 1;
        if ($available > 0 && $is_cookie_ok) {
            echo "<td><a href='app.php?a={$row['account']}&p={$row['password']}&y" . ($row['pay'] == -1 ? '' : '=' . $row['pay']) . "' style='color: black'>约{$available}h</a></td>";
            echo "<td>
            <a onclick='show_password(\"{$row['password']}\",\"{$row['pay']}\")' class='opt' style='cursor: pointer'>显示密码</a>
            <a class='opt' href='orders.php?account={$row['account']}' target='_blank'>订单记录</a>";

            echo $row['pay'] == '-1' ? "<a class='opt' href='app.php?a={$row['account']}&p={$row['password']}&s' target='_blank'>设置支付密码</a>" : '';

            echo "</td>";
        } else {
            echo "<td><a href='app.php?a={$row['account']}&p={$row['password']}' class='opt'>更新</a></td>";
            echo "<td>Cookie不可用</td>";
        }

        echo "</tr>";
    }
    ?>
</table>

<div style="text-align: center;">
    <ul class="pagination">
        <?php
        $pagination = new Pagination($total, $page_size, 'index.php?p=');
        $pagination->setPageNib(10);
        $pagination->pages($page);
        ?>
    </ul>
</div>
<div id="modal-container">
    <div class="modal-background">
        <div class="modal" onclick="">
            <h3 style="margin-top: -2pc">密码</h3>
            <div style="text-align: left">
                <p style="margin: 0">登录：<span id="pass_login">******</span></p>
                <p style="margin: 0">支付：<span id="pass_pay">******</span></p>
            </div>
            <p><a href="https://lipin.ctrip.com/" target="_blank"
                  style="color: blue;font-size: 14px;">打开 携程礼品卡 网站</a></p>
            <p style="margin-bottom: -2pc">
                <a style="background-color: #009bd5;color: white;padding: 8px 30px;border-radius: 5px;font-size: 12px;cursor: pointer"
                   onclick="clo()">关闭</a>
            </p>
        </div>
    </div>
</div>
<script src="https://cdn.lifanko.cn/jquery-2.1.1.min.js"></script>
<script>
    var model = $('#modal-container');

    var pass_login = document.getElementById("pass_login");
    var pass_pay = document.getElementById("pass_pay");

    function show_password(pass, pay) {
        pass_login.innerText = pass;
        pass_pay.innerText = pay === '-1' ? '******' : pay;

        model.removeAttr('class').addClass('two');
        $('body').addClass('modal-active');
    }

    function clo() {
        model.addClass('out');
        $('body').removeClass('modal-active');
    }
</script>
</body>
</html>
